MQTT Interface

Path: ProjectView> Config > Interfaces > double-click MQTT

Use MQTT Interface to publish data according to the MQTT standard.

Note that a tag or an alarm, to be transferred through the MQTT protocol, must be defined within a group.

Parameter Description
Enable MQTT Interface Main flag to activate MQTT service.
The selected groups of tags will be published to the MQTT broker.
Enable Alarms The selected groups of alarms will be published to the MQTT broker.
Alarms are published whenever there is a change in the alarm status.

Tags configuration

Parameter Description
Enable Enable tags included within the group to trigger the publication "Data (Pub)". The tags included in the group can be updated by the subscription "Data (Sub)".
Tag Group List of tags that will be transferred when the assigned policy conditions will be satisfied.
QoS

QoS to use

0 = Delivered at most once (Fire and forget) which means no confirmation

1 = Delivered at least once, which means confirmation required

2 = Delivered exactly once, which means a 4 step handshake is done

Retain This flag defines whether the message is saved by the broker as the last known good value for a specified topic. When a new client subscribes to a topic, they receive the last message that is retained on that topic.
Persistence

When true, the messages with QoS greater than 0 are queued into the file system file to be available even after a panel reset or when a broken communication with the MQTT server is reestablished.

Policy Defines the criteria for deciding when to publish the value of a tag. When it is empty, the "Default push policy", defined on top of the table, is used.
Manage push policy

A policy consists of a trigger criterion and several (optional) conditions that must be verified in order for the tag value to be transmitted.

Trigger

Parameter Description
Timer

Publish is performed continuously even value is not changing.

  • Interval (ms)
    Cyclical publication time
On change

Publish is performed when a tag value changes.

  • Min interval (ms)
    Value check interval
  • Deadband
    The difference, from previous publish, that must be found to trigger the new publish.
  • Use percentual
    Dead band value express in percentage
  • Tag Name
    Tags to be checked to activate the publication. If empty, the tag to be published is used.

Conditions

Conditions contain folders of conditions. Each folder can be of two types:

All folders must be validated to have the transmission requested by the trigger. A folder of type "All the following condition are met" is validated when all the contained conditions are true while a folder of type "Any of the following conditions are met" is validated when at least one contained condition is true.

Tags interface

The "Tags Interface" allows you to define tags that will be used to exchange information about the status of the MQTT interface.

Parameter Description Data Type
Enable

Control the status of the MQTT interface.

If this parameter is empty (not attached to a tag), the MQTT interface will be always enabled.

  • 0 = Disabled
  • 1 = Enabled

boolean

Read Write

Status

Report the status of the MQTT interface.

  • 0 = Disconnected
  • 1 = Connected
  • 2 = Connecting
  • 3 = Disconnecting

unsignedInt

Read Only

Last error

In case of errors, it will report the error message.

You can write an empty string to clear the error message.

string

Read Write

Messages sent Amount of messages sent from the HMI Device to the remote MQTT Server.

unsignedInt

Read Only

Messages received Amount of messages received by the HMI Device from the remote MQTT Server.

unsignedInt

Read Only

Queue length The number of pending messages to be sent that are temporarily cached in the local buffer.

unsignedInt

Read Only

Queue size The maximum number of messages that can be temporarily cached in the local buffer.

unsignedInt

Read Only

Settings

Topic Description
Max pending messages The number of messages that can be queued in RAM when there are communication errors. Queue messages will be released as soon as the MQTT Server returns reachable.
Defaults Values of "QoS", "Retain" and "Persistence" parameter to use for the topics that are not defined inside the "Tags configuration" table.

Topic and Payload

There are five types of supported topics:

Topic Description
Birth This is a special topic that is publish only one time when HMI device start.
Will

Special topic that is published when device starts but stored and kept hidden by the MQTT Broker. It will be published by the MQTT Broker if it detects that the client has disconnected ungracefully.

Data (Pub) Topic is used to publish the tags' values following the transmission policies associated with tag groups.
Data (Sub) Topic is used to subscribe to tags. The payload is the template used to recognize the values of the received tags.
Alarm Topic used to publish alarms

For each topic, the payload defines the structure of the associated value. Note that in topic and payload definitions can be used placeholders.

Placeholder Description
${clientId} MQTT Client ID
${timestamp} Return the time when the tag got updated in UTC format
${localTimestamp} Return the time when the tag got updated in local format
${currentTimestamp} Return the time when the MQTT message publish
${protocolName} Name of the protocol associated to a tag
${tagGroup} Name of the group the tag belongs to
${tagName} Name of the tag
${alarmGroup} Name of the group the alarm belongs to
${alarmName} Name of alarm
${value} Last known value of the tag
${activeValue} Value of the tag when the alarm became active
${quality} Quality (i.e. reliability) of the tag
${activeTimestamp} Timestamp of the last event that raised the alarm
${inactiveTimestamp} Timestamp of the last event that ceased the alarm condition
${ackTimestamp} Timestamp when the operator acknowledge the alarm
${description} Alarm description
${customField1} Alarm Custom Field 1
${customField2} Alarm Custom Field 2
${state} Alarm State
${severity} Alarm Severity
${lowLimit} Alarm “Low limit”
${highLimit} Alarm “High limit”
${[0]} If available in the alarm description, the value of the first live tag, [1] the second, etc.
${[Tag1]} If available in the alarm description, the value of "Tag1" live tag
${any} A generic label. Useful in the subscribe payloads

JSON Payload

When the JSON format is selected, the quotation marks are added around string values to conform to the JSON syntax.

With the use of the JSON format is possible to optimize the communication to include multiple messages inside a single message. When the "Message aggregation" is selected, the messages are sent to MQTT Server after the selected timeout expired or when the message to send reaches the select size.

Multiple Tags

Using JSON format, in the subscribe/publish topics is possible to manage multiple tags as for the following examples:

To match an incoming message like:

{ "x": { "tagName": "Tag1", "value": 1 }, "y": { "tagName": "Tag2", "value": 2 } }

you can use pattern:

{ "${any}": { "tagName": "${tagName}", "value": "${value}" } }

To match an incoming message like:

[ { "tagName": "Tag1", "value": 1 }, { "tagName": "Tag2", "value": 2 } ]

you can use pattern:

[ { "tagName": "${tagName}", "value": "${value}" } ]

To match an incoming message like:

{ "Tag1": { "value": 1 }, "Tag2": { "value": 2 } }

you can use pattern:

{ "${tagName}": { "value": "${value}"} }

To match an element, or all elements, of an array incoming message like:

{ "Tag1": { "value": "[1, 2, 3, 4, 5, 6, 7, 8]" } }

you can use pattern:

{ "${tagName}": { "value": "${value.1}"} }

{ "${tagName}": { "value": "${value}"} }

For published topics, a tag/group of tags is required to establish the trigger condition but the message can now contain other tag values using live tag syntax. The trigger tag can even be omitted in the payload pattern.

Examples:

{ "tag1" : "${[Tag1]}", "tag2" : "${[Tag2]}" }

For subscribed topics, the same live tag syntax can be used to write any tag value (note that only tags listed from the trigger condition can be written).

Examples:

{ "tag1" : "${[Tag1]}", "tag2" : "${[Tag2]}" }

{ "t" : "${tagName}", "v" : "${value}", "tag2" : "${[Tag2]}" }"

MQTT Broker Settings

Current supported MQTT Broker are:

Note that some parameters depend on the broker has chosen.

Generic MQTT Broker
Parameter Description
Broker address

Name or IP address of the MQTT server with the port number (e.g. "127.0.0.1:1883")

Generally, the default TCP/IP port is 1883, or the port 8883 when MQTT over SSL is used.

Client ID The client identifier is an identifier of each MQTT client connecting to an MQTT broker. You can write what you prefer, but it has to be unique per broker. The broker uses it for identifying the client and the current state of the client.
Username
Password
If the MQTT broker is configured to require client authentication using a valid user name and password
Keep-alive time (s) Time interval before sending a PING request to the server when there are no data flows (useful to know if both client and server are still alive and reachable).
Use clean session When the clean session flag is set to false, the broker creates a persistent session for the client. All information and messages are preserved until the next time that the client requests a clean session. If the clean session flag is set to false and the broker already has a session available for the client, it uses the existing session and delivers previously queued messages to the client.
Use legacy The “Use legacy” flag makes client comply with MQTT spec 3.1

Enable TLS

If the MQTT server is configured to works over TLS connection, the HMI device must provide its own certificate to the server. Even it's not mandatory, each client should have its own certificate (however it is possible you can deploy the same certificate to all clients).

It is required that both server and client certificates are signed by the same authority.

Parameter Description
Enable TLS Enable the TLS encryption
CA Certificate Public certificate of the CA that has signed the server certificate on the Mosquitto Broker
Client Certificate Public certificate of the HMI Device. Must be signed from the CA Certificate
Client Key Private key associated with the client certificate
TLS Version

TLS Version to use (must be aligned with the encryption level used from the MQTT Broker)

  • tlsv 1
  • tlsv 1.1
  • tlsv 1.2
Insecure This option disables verification of the server host name in the server certificate. This can be useful when testing initial server configurations but makes it possible for a malicious third party to impersonate your server through DNS spoofing, for example. Use this option in testing only.

Note that you can use the "attach to tag" to entered the MQTT parameters at runtime using, e.g., macros, JavaScript or a configuration page. This could be useful to have different values (e.g. for the ClientID) even downloading the same project to different HMI devices.

If you use tags to define MQTT settings (e.g. Client ID), be sure to not include these tags into the tags list exchanged with the MQTT server to avoid to receive back wrong settings.

The string Tags used for the certificate must be great enough (e.g. 2.048 bytes) to contain the entire certificate. The format of the certificates must be ASCII with the first and the last text line included as for the below example.

MQTT Broker Example

Here is a little example that explains how to configure an application to communicate with an MQTT server. In this example, we configure the HMI device to communicate with an open-source MQTT broker (https://mosquitto.org) using certificates. The certificates will be created using a public OpenSSL-Win32 library (https://www.openssl.org).

Generate the certificates

The following script file will create a couple of server and client certificates and a public Certificate Authority that will be used to sign server and client certificates and to verify the authenticity of these certificates.

File: CreateCertificates.cmd

@echo off set OpenSSL="C:\Program Files (x86)\OpenSSL-Win32\bin\openssl.exe" rem Generate self signed CA certificate (Certificate Autority) %OpenSSL% req -nodes -batch -new -x509 -days 1000 -keyout ca.key -subj "/CN=Broker/O=company.com" -out ca.crt rem Generate MQTT Server private key %OpenSSL% genrsa -out server.key 2048 rem Generate MQTT Server certificate signed request %OpenSSL% req -batch -new -key server.key -subj "/CN=localhost/O=company.com" -out server.csr rem Sign the MQTT Server certificate %OpenSSL% x509 -req -days 1000 -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt rem Generate HMI Client private key %OpenSSL% genrsa -out client.key 2048 rem Generate HMI Client Server certificate signed request %OpenSSL% req -batch -new -key client.key -subj "/CN=client/O=company.com" -out client.csr rem Sign the HMI Client certificate %OpenSSL% x509 -req -days 1000 -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt rem Remove unnecessary files del *.rnd *.srl *.csr pause

Note the server hostname is localhost (/CN=localhost), this means that you cannot use the secure connection if in the Broker address parameter you cannot write the "localhost" domain. You can use the "localhost" domain only if both the MQTT Server and the HMI device are running on the same device otherwise, to be able to reach the MQTT server, you must use the IP Address and the "Insecure" flag.

MQTT Broker configuration

The server certificate (server.crt, server.key) and the authority certificate (ca.crt) must be place inside a subfolder of the MQTT folder, e.g. inside the "certs" subfolder.

The "mosquitto.conf" file has to be configured to use the TLS support

# ================================================================= # Default listener # ================================================================= ... (omiss) ... # Port to use for the default listener. #port 1883 port 8883 # ----------------------------------------------------------------- # Certificate based SSL/TLS support # ----------------------------------------------------------------- ... (omiss) ... #cafile #capath cafile certs/ca.crt certfile certs/server.crt keyfile certs/server.key tls_version tlsv1.2

MQTT Broker can be started using the below command from a dos command window:

mosquitto -v -c mosquitto.conf

MQTT Client

For testing purposes, it could be useful to start an MQTT client with the subscription of all the topics so that you can see the messages that will be exchanged with HMI Device. Since we are using TLS communication, we must provide the client certificate. We can copy client.crt, client.key and the authority certificate ca.crt inside the certs-client subfolder.

So the command to activate an MQTT client is:

mosquitto_sub --cafile certs-client\ca.crt --cert certs-client\client.crt --key certs-client\client.key -p 8883 -t /#

HMI Device

To configure the HMI device we must provide:

To perform the first tests, you can leave the default values on topics and payloads and configure the alarms groups and tags groups that you want to transfer to the MQTT broker.